<template>
  <t-popup expand-animation placement="bottom-right" trigger="click">
    <template #content>
      <div class="header-msg">
        <div class="header-msg-top">
          <p>{{ $t('notice.label.center') }}</p>
          <div>
            <t-button size="small" shape="circle" theme="primary" @click="onRefresh">
              <template #icon><RefreshIcon /></template>
            </t-button>
            <t-button v-if="notificationStore.msgData?.totalRow > 0" class="clear-btn" variant="text" theme="primary" @click="setRead('all')"
              >{{ $t('common.clean') }}</t-button
            >
          </div>
          
        </div>
        <div v-if="notificationStore.msgData.totalRow > 0" style="margin-top:60px;padding-bottom: 40px;">
          <t-list class="narrow-scrollbar"
            style="max-height: 400px"
            :async-loading="asyncLoading"
            :split="false" 
            @load-more="loadMore"
            @scroll="scrollHandler">
            <t-list-item v-for="(item, index) in notificationStore.msgData.records" :key="`scroll${item}`" @click="readNotice(item)">
              <div>
                <p class="msg-content">{{ item.title }}</p>
              </div>
              <p class="msg-time">{{ dateFormatByMomentTimezone(item.createTime) }}</p>
              <template #action>
                <t-button size="small" variant="outline" @click.stop="setRead('radio', item)"> {{ $t('notice.setread') }} </t-button>
              </template>
            </t-list-item>
          </t-list>
        </div>

        <div v-else class="empty-list">
          <img src="https://tdesign.gtimg.com/pro-template/personal/nothing.png" />
          <p>{{ $t('notice.nothaveyet') }}</p>
        </div>
        <div class="header-msg-bottom">
          <t-button
            v-if="notificationStore.msgData.totalRow > 0"
            class="header-msg-bottom-link"
            variant="text"
            theme="default"
            block
            @click="goDetail"
            style="color:var(--td-brand-color-active);"
            >{{ $t('common.view.all') }}</t-button
          >
        </div>
      </div>
    </template>
    <t-badge :count="notificationStore.msgData.totalRow" :offset="[4, 4]">
      <t-button theme="default" shape="square" variant="text">
        <t-icon name="mail" />
      </t-button>
    </t-badge>
  </t-popup>
  <t-dialog
      closeOnEscKeydown
      mode="full-screen"
      :footer="false"
      v-model:visible="visible"
      :header="tdialogContent.title"
    >
    <div style="text-align: center"><TagDict :dictType='SYS_NOTICE_TYPE' :value='tdialogContent.type' /></div>
    <div style="text-align: center"><Calendar1Icon /><span>{{ dateFormatByMomentTimezone(tdialogContent.createTime) }}</span></div>
    <div style="text-align: center" v-html="tdialogContent.content"></div>
    </t-dialog>
</template>

<script setup lang="ts">
import {
  Calendar1Icon,
} from 'tdesign-icons-vue-next';
import { RefreshIcon } from 'tdesign-icons-vue-next';
import { useRouter } from 'vue-router';
import { useNotificationStore,useUserStore } from '@/store';
import { computed, onMounted, ref, watch } from 'vue';
import { ListProps } from 'tdesign-vue-next';
import { dateFormatByMomentTimezone } from '@/utils/date'
import { PageNoticeReq, PageNoticeRes, UserNoticePageReq } from '@/api/system/notice/types';
import { Reply } from '@noear/socket.d/transport/core/Entity';
import { Result } from '@/types/axios';
import { PageResponse } from '@/api/types';
import { ResultEnum } from '@/enums/httpEnum';
import i18n from "@/i18n";
import { SYS_NOTICE_TYPE } from '@/constants/dictTypes';

const visible = ref(false);
const router = useRouter();
const notificationStore = useNotificationStore();
const asyncLoadingRadio = ref('load-more');
const asyncLoading = computed(() => {
  if (asyncLoadingRadio.value === 'loading-notData') {
    return ()=>i18n.global.t('common.notData');
  }
  return asyncLoadingRadio.value;
});
const params=ref<UserNoticePageReq>({
  pageNumber: 1,
  pageSize: 10,
  readStatus: 1,
})

const tdialogContent = ref<PageNoticeRes>({
  title: '',
  id: '',
  type: 0,
  target: 0,
  content: '',
  status: 0,
  remark: '',
  userName: '',
  createTime: undefined,
  readStatus: 0
});

/**
 * 通知中心滚动事件
 */
const scrollHandler: ListProps['onScroll'] = async (e) => {
  if(e.scrollBottom <= 1 ){
    if(asyncLoadingRadio.value == 'loading-notData'){
      return;
    }
    asyncLoadingRadio.value = 'loading';
    params.value.pageNumber=Number(params.value.pageNumber)+1;
    await requestNotice(false);
  }
}

/**
 * 通知中心点击加载更多事件
 */
 const loadMore: ListProps['onLoadMore'] = async () => {
    asyncLoadingRadio.value = 'loading';
    params.value.pageNumber=Number(params.value.pageNumber)+1;
    await requestNotice(false);
}

/**
 * 请求获取通知
 */
const requestNotice = async (refresh:boolean)=>{
    let reply:Reply=await notificationStore.pageNotice(params.value);
    let res:Result<PageResponse<Array<PageNoticeRes>>>=JSON.parse(reply.dataAsString());
    if(ResultEnum.SUCCESS == res.code){
      console.log('res',res)
      if(res.result.records.length>0){
        params.value.pageNumber=res.result.pageNumber
        if(params.value.pageSize >= res.result.totalRow){
          asyncLoadingRadio.value = 'loading-notData'
        }else{
          asyncLoadingRadio.value = 'load-more';
        }
        notificationStore.setMsgDataPageNoticeRes(res.result,refresh);
      }else{
        asyncLoadingRadio.value = 'loading-notData'
      }
    }
}

/**
 * 读取通知
 */
 const readNotice = async (item: PageNoticeRes) => {
  visible.value = true;
  setTimeout(async () => {
    await notificationStore.read([item.id]);
  }, 1);
  
  tdialogContent.value = item;
  visible.value = true;
};

/**
 * 刷新通知中心
 */
const onRefresh = async ()=>{
  params.value={
    pageNumber: 1,
    pageSize: 10,
    readStatus: 1,
  }
  await requestNotice(true);
}

const setRead = async (type: any, item?: PageNoticeRes) => {
  // const changeMsg = msgData.value;
  if (type === 'all') {
    await notificationStore.read(notificationStore.msgData.records.map((item:PageNoticeRes) => item.id));
   
  } else {
    await notificationStore.read([item.id]);
  }
  // store.setMsgData(changeMsg);
};

const goDetail = () => {
  //'/system/notice/secondary'
  router.push({name:'secondary'});
};

onMounted(async () => {
  await notificationStore.initysNoticeSocketd(params.value);
  params.value.pageNumber=notificationStore.msgData.pageNumber
  console.log('params',params)
});

</script>

<style lang="less" scoped>
.header-msg {
  width: 400px;
  margin: calc(0px - var(--td-comp-paddingTB-xs)) calc(0px - var(--td-comp-paddingLR-s));
 
  .header-msg-top {
    position: absolute;top:0;
    z-index:99;
    width:100%;
    background: var(--td-bg-color-container);
    border-bottom: 1px solid #d5d5d5;
    padding-bottom: 10px;

    :deep(.t-button--shape-circle.t-size-s){
      width: var(--td-comp-size-xs) + 10;
    }
  }

  .header-msg-bottom {
    position: absolute;
    bottom: 0;
    z-index: 99;
    background: var(--td-bg-color-container);
    width: 100%;
  }

  .empty-list {
    height: calc(100% - 120px);
    text-align: center;
    padding-top: 135px;
    font: var(--td-font-body-medium);
    color: var(--td-text-color-secondary);

    img {
      width: var(--td-comp-size-xxxxl);
    }

    p {
      margin-top: var(--td-comp-margin-xxl);
    }
  }

  &-top {
    position: relative;
    font: var(--td-font-title-medium);
    color: var(--td-text-color-primary);
    text-align: left;
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl) 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .clear-btn {
      right: calc(var(--td-comp-paddingTB-l) - var(--td-comp-paddingLR-xl));
    }
  }

  &-bottom {
    align-items: center;
    display: flex;
    justify-content: center;
    padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-s);
    border-top: 1px solid var(--td-component-stroke);

    &-link {
      text-decoration: none;
      cursor: pointer;
      color: var(--td-text-color-placeholder);
    }
  }

  .t-list {
    // height: calc(100% - 104px);
    padding: var(--td-comp-margin-s) var(--td-comp-margin-s);


    :deep(.t-list__load){
      color: var(--td-text-color-secondary);
    }
  }

  .t-list-item {
    overflow: hidden;
    width: 100%;
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-l);
    border-radius: var(--td-radius-default);
    font: var(--td-font-body-medium);
    color: var(--td-text-color-primary);
    cursor: pointer;
    transition: background-color 0.2s linear;

    &:hover {
      background-color: var(--td-bg-color-container-hover);

      .msg-content {
        color: var(--td-brand-color);
      }

      .t-list-item__action {
        button {
          bottom: var(--td-comp-margin-l);
          opacity: 1;
        }
      }

      .msg-time {
        bottom: -6px;
        opacity: 0;
      }
    }

    .msg-content {
      margin-bottom: var(--td-comp-margin-s);
    }

    .msg-content {
      color: var(--td-text-color-secondary);
    }

    .t-list-item__action {
      button {
        opacity: 0;
        position: absolute;
        right: var(--td-comp-margin-xxl);
        bottom: -6px;
      }
    }

    .msg-time {
      transition: all 0.2s ease;
      opacity: 1;
      position: absolute;
      right: var(--td-comp-margin-xxl);
      bottom: var(--td-comp-margin-l);
      color: var(--td-text-color-secondary);
    }
  }
}
</style>
